package com.example.juc.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {

    public static void main(String[] args) {
        //A a = new A();
        B a = new B();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                a.increment();
            }
        }, "1").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                a.decrement();
            }
        }, "2").start();

    }

}

class A {

    private int num = 0;

    public synchronized void increment() {
        while (num != 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        num++;
        System.out.println("线程：" + Thread.currentThread().getName() + "，num===>" + num);
        this.notifyAll();
    }

    public synchronized void decrement() {
        while (num == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        num--;
        System.out.println("线程：" + Thread.currentThread().getName() + "，num===>" + num);
        this.notifyAll();
    }
}

class B {

    private int num = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increment() {
        lock.lock();

        try {
            while (num != 0) {
                condition.await();
            }
            num++;
            System.out.println("线程：" + Thread.currentThread().getName() + "，num===>" + num);
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();

        try {
            while (num == 0) {
                condition.await();
            }
            num--;
            System.out.println("线程：" + Thread.currentThread().getName() + "，num===>" + num);
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
